package com.dubbo.gmail.controller;

import com.dubbo.gmail.ConsumerApplication;
import com.dubbo.gmail.api.model.UserModel;
import com.dubbo.gmail.api.service.HelloService;
import com.dubbo.gmail.remotecache.RemoteCacheConsumer;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class HelloController {

    private Map<String, ReferenceBean> urlReferenceBeanMap = new HashMap<>();
    private URL url = new URL("dubbo", "localhost",20870);//更改不同的Dubbo服务暴露的ip地址&端口

    @DubboReference(check = false, loadbalance = "roundrobin")
    HelloService helloService;

    @Autowired
    RemoteCacheConsumer remoteCacheConsumer;

    @RequestMapping("/ping")
    @ResponseBody
    public String ping() {
        return "pong";
    }

    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        return helloService.sayHello("test");
    }

    @RequestMapping("/testId")
    @ResponseBody
    public String testId() {

        String s = url.setServiceInterface(HelloService.class.getName()).toString();
        ReferenceBean<HelloService> referenceBean = urlReferenceBeanMap.get(s);
        if(referenceBean == null){
            referenceBean = new ReferenceBean<>();
            referenceBean.setApplicationContext(remoteCacheConsumer.getApplicationContext());
            referenceBean.setInterface(com.dubbo.gmail.api.service.HelloService.class);
            referenceBean.setUrl(s);
            try {
                referenceBean.afterPropertiesSet();
            } catch (Exception e) {
                e.printStackTrace();
            }
            urlReferenceBeanMap.put(s, referenceBean);
        }
        try {
            HelloService helloService = referenceBean.get();
            return helloService.sayHello("Tester");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "empty";
    }

    @RequestMapping("/cacheUser")
    @ResponseBody
    public String cacheUserModel() {
        return helloService.cacheUserModel(new UserModel(123, "fff"));
    }
}
